import { Injectable } from '@nestjs/common';
import { Cat } from './entities/cat.entity';
import { CreateCatDto } from './dto/create-cat.dto';
import { NotFoundException } from '@nestjs/common';
import { FilesService } from '../files/files.service';

@Injectable()
export class CatsService {
  private cats: Cat[] = [];
  private nextId = 1;

  constructor(private readonly filesService: FilesService) {}

  create(createCatDto: CreateCatDto): Cat {
    const newCat: Cat = {
      id: this.nextId++,
      name: createCatDto.name,
      age: createCatDto.age,
      breed: createCatDto.breed,
      imageUrl:
        createCatDto.imageUrl || this.generateRandomCatImage(createCatDto.name),
      createdAt: new Date(),
    };
    this.cats.push(newCat);
    return newCat;
  }

  async createWithAvatar(
    createCatDto: CreateCatDto,
    file: Express.Multer.File,
  ): Promise<Cat> {
    // 处理上传的图片
    const avatar = await this.filesService.processImage(file);

    const newCat: Cat = {
      id: this.nextId++,
      name: createCatDto.name,
      age: createCatDto.age,
      breed: createCatDto.breed,
      imageUrl: avatar.path,
      createdAt: new Date(),
    };
    this.cats.push(newCat);
    return newCat;
  }

  findAll(): Cat[] {
    return this.cats;
  }

  findOne(id: number): Cat {
    const cat = this.cats.find((cat) => cat.id === id);
    if (!cat) {
      throw new NotFoundException(`猫咪 ID ${id} 未找到`);
    }
    return cat;
  }

  private generateRandomCatImage(name: string): string {
    // 使用猫咪图片生成服务
    const colors = ['red', 'blue', 'green', 'yellow', 'purple', 'pink'];
    const randomColor = colors[Math.floor(Math.random() * colors.length)];
    return `https://placekitten.com/200/300?text=${encodeURIComponent(name)}&color=${randomColor}`;
  }
}
